#include "Socket.hpp"
#include <sys/epoll.h>

class EpollServer
{
    const static int defaultfd = -1;
    const static int size = 4096;
public:
    EpollServer(int port)
        :_listensock(std::make_unique<TcpSocket>())
    {
        //创建listen_sock
        _listensock->BuildTcpListenSocket(port);

        //创建epoll模型
        _epfd = epoll_create(256);
        if(_epfd < 0)
        {
            LOG(LogLevel::FATAL) << "epoll_create error";
            exit((int)exit_code::EPOLL_CREATE_ERR);
        }

        //将监听文件描述符加入epoll模型
        epoll_event event;
        event.events = EPOLLIN; // 读
        event.data.fd = _listensock->Fd();

        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock->Fd(), &event);
        if(n < 0)
        {
            LOG(LogLevel::FATAL) << "epoll_ctl error";
            exit((int)exit_code::EPOLL_CTL_ERR);
        }
    }

    void Start()
    {
        _isrunning = true;
        int timeout = 1000;
        while(_isrunning)
        {
            int n = epoll_wait(_epfd, _revs, size, timeout);
            switch(n)
            {
            case -1:
                LOG(LogLevel::ERROR) << "epoll_wait error";
                break;
            case 0:
                LOG(LogLevel::INFO) << "timeout";
                break;
            default:
                Dispather(n);
                break;
            }
        }
        _isrunning = false;
    }

    void Dispather(int n)
    {
        //循环处理就绪事件
        for(int i = 0; i < n; i++)
        {
            //读事件就绪
            if(_revs[i].events & EPOLLIN)
            {
                //监听就绪
                if(_revs[i].data.fd == _listensock->Fd())
                {
                    Accepter();
                }
                else // 交互就绪
                {
                    Recver(_revs[i].data.fd);
                }
            }
        }
    }

    //链接管理器
    void Accepter()
    {
        //获取客户端IP和端口
        InetAddr client;
        int sockfd = _listensock->Accept(&client);
        if(sockfd != -1) // 将新的文件描述符加入epollm模型
        {
            epoll_event event;
            event.events = EPOLLIN; // 读
            event.data.fd = sockfd;

            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &event);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
            }
        }
    }

    //IO处理器
    void Recver(int sockfd)
    {
        char buff[1024];
        int n = recv(sockfd, buff, sizeof(buff) - 1, 0);
        if(n > 0) // 读到了
        {
            buff[n] = '\0';
            LOG(LogLevel::INFO) << "client say: " << buff;
        }
        else if(n == 0) // 客户端退出
        {
            LOG(LogLevel::INFO) << "客户端退出";

            //先移除，再关闭，因为epoll只能移除合法的fd，关闭后fd就不合法了
            //模型中去除对应sockfd
            epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);

            //关闭文件
            close(sockfd);          
        }
        else // 读取错误
        {
            LOG(LogLevel::ERROR) << "读取错误";
            
            //先移除，再关闭，因为epoll只能移除合法的fd，关闭后fd就不合法了
            //模型中去除对应sockfd
            epoll_ctl(_epfd, EPOLL_CTL_DEL, sockfd, nullptr);

            //关闭文件
            close(sockfd);   
        }
    }

    void Stop()
    {
        _isrunning = false;
    }
private:
    std::unique_ptr<Socket> _listensock;
    bool _isrunning = false;
    
    int _epfd = defaultfd;
    epoll_event _revs[size];
};